package com.project.lvshi.controller.aiSeek;

import com.project.lvshi.domain.*;
import com.project.lvshi.service.AiSeekItemService;
import com.project.lvshi.service.SysSeekItemService;
import com.project.lvshi.service.UserService;
import com.project.lvshi.utils.TokenUtils;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletion;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatCompletionResponse;
import io.github.lnyocly.ai4j.platform.openai.chat.entity.ChatMessage;
import io.github.lnyocly.ai4j.service.IChatService;
import io.github.lnyocly.ai4j.service.PlatformType;
import io.github.lnyocly.ai4j.service.factor.AiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/ai")
@Slf4j
public class OllamChatController {

    //注入Ai服务
    @Autowired
    private AiService aiService;

    @Autowired
    private AiSeekItemService sysSeekItemService;
    @Autowired
    private UserService userService;

    @PostMapping("/chat")
    public void getChatMessage(@RequestBody AiOnline aiOnline)throws Exception {

        String Content=aiOnline.getContent();
        //创建问题
        String question="你是智能法律咨询平台的Ai助手，名字为deepSeek,下面回答的内容字数，控制在200字左右，内容为:" + Content+"如果无法回答，请回复:请咨询相关律师";
        //获取OLLAMA的聊天服务
        IChatService chatService = aiService.getChatService(PlatformType.OLLAMA);
        //创建请求参数
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model("deepseek-r1:1.5b")
                .message(ChatMessage.withUser(question))
                .build();
        System.out.println(chatCompletion);
        //发送chat请求
        ChatCompletionResponse chatCompletionResponse = chatService.chatCompletion(chatCompletion);
        //获取聊天内容和token消耗
        String content = chatCompletionResponse.getChoices().get(0).getMessage().getContent().getText();
        System.out.println("内容为:" + content);
        long totalTokens = chatCompletionResponse.getUsage().getTotalTokens();
        System.out.println("总token消耗:" + totalTokens);

        //分割思考</think>的内容
        String[] split = content.split("</think>");
        //将思考后的内容，重新封装再content
        content = split[1];
        //封装内容
        aiOnline.setContent( content);

//         String content=  "12的说法3";

        String seekId = aiOnline.getSeekId();

        AiSeekItem sysSeekItem = new AiSeekItem();
        sysSeekItem.setSeekId(seekId);
        //添加内容
        sysSeekItem.setContent(content);
        //获取用户id
        String id = TokenUtils.getUserIdByToken();
        User user = userService.getById(id);
        sysSeekItem.setUserId(id);
        sysSeekItem.setAvatar(user.getAvatar());
        //保存
        sysSeekItemService.save(sysSeekItem);

    }
//http://localhost:8080/ai/chat?question=
}
